package org.yzh.commons.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
@Data
public class PageResultDTO<T> {


    private Integer total;
    private List<T> records;
    /**
     * 是否存在更多
     */
    private Boolean hasMore;

    public static <T> PageResultDTO<T> create(Integer total, List<T> records) {
        PageResultDTO<T> pageResultDTO = new PageResultDTO<>();
        pageResultDTO.setTotal(total);
        pageResultDTO.setRecords(records);
        return pageResultDTO;
    }

    public static <T> PageResultDTO<T> create(List<T> records) {
        PageResultDTO<T> pageResultDTO = new PageResultDTO<>();
        pageResultDTO.setTotal(0);
        pageResultDTO.setRecords(records);
        pageResultDTO.setHasMore(true);
        return pageResultDTO;
    }


    public static <T, S> PageResultDTO<T> convert(IPage<S> page, Function<S, T> function) {
        PageResultDTO<T> result = create((int) page.getTotal(), null);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            result.setRecords(Collections.emptyList());
            return result;
        }

        result.setRecords(page.getRecords()
                .stream()
                .map(function)
                .collect(Collectors.toList()));

        return result;
    }

    public static <T> PageResultDTO<T> empty() {
        PageResultDTO<T> resultDTO = create(0, Collections.emptyList());
        resultDTO.setHasMore(false);
        return resultDTO;
    }
}
